package com.fast.framework.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fast.framework.config.redis.RedisCache;
import com.fast.framework.constant.CacheConstants;
import com.fast.framework.core.domain.User;
import com.fast.framework.core.model.RegisterBody;
import com.fast.framework.core.service.IRegisterService;
import com.fast.framework.core.service.IUserService;
import com.fast.framework.exception.user.CaptchaException;
import com.fast.framework.exception.user.CaptchaExpireException;
import com.fast.framework.utils.SecurityUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("registerServiceImpl")
public class RegisterServiceImpl implements IRegisterService {

    @Resource
    private IUserService userService;
    @Resource
    private RedisCache redisCache;

    /**
     * 注册用户
     *
     * @param registerBody 注册用户实体
     * @return 注册的信息
     */
    @Override
    public String register(RegisterBody registerBody) {
        // 返回的消息
        String msg;

        User registerUser = new User();

        //验证验证码
        validateCaptcha(registerBody.getCode(), registerBody.getUuid());

        if (StrUtil.isEmpty(registerBody.getUserName())) {
            msg = "用户账号不能为空";
        } else if (StrUtil.isEmpty(registerBody.getPassword())) {
            msg = "用户密码不能为空";
        } else if (registerBody.getPassword().length() < 5 || registerBody.getPassword().length() > 20) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (userService.checkUserNameUnique(registerBody.getUserName())) {
            msg = "保存用户'" + registerBody.getUserName() + "'失败，注册账号已存在";
        } else {
            registerUser.setUserId(SecurityUtils.generationID(10));
            //设置昵称
            registerUser.setNickName(registerBody.getNickName());
            //系统账号分配
            registerUser.setUsername(registerBody.getUserName());
            registerUser.setPhone(registerBody.getUserName());

            registerUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
            registerUser.setDelTags(true);//启用
            boolean regFlag = userService.registerUser(registerUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                msg = "注册成功";
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
}
